from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium import webdriver
import time


class TableHandler:
    TABLE_LOCATOR = ("xpath", "//div[@class='web-tables-wrapper']")
    ROWS_LOCATOR = ("xpath", ".//div[@class='rt-tr-group']")
    CELLS_LOCATOR = ("xpath", ".//div[@class='rt-td']")

    def __init__(self, driver):
        self.driver: WebDriver = driver

    @property
    def _table(self) -> WebElement:
        return self.driver.find_element(*self.TABLE_LOCATOR)

    @property
    def _rows(self) -> list[WebElement]:
        table = self._table
        return table.find_elements(*self.ROWS_LOCATOR)

    @property
    def row_count(self) -> int:
        return len(self._rows)

    def get_cell_content(self, row_number, column_number):
        row = self._rows[row_number - 1]
        cell = row.find_elements(*self.CELLS_LOCATOR)[column_number - 1]
        return cell.text

    def get_row_content(self, row_number):
        row = self._rows[row_number - 1]
        return [cell.text for cell in row.find_elements(*self.CELLS_LOCATOR)]

    def get_column_content(self, column_number):
        column_content = []
        for row in self._rows:
            cells = row.find_elements(*self.CELLS_LOCATOR)
            column_content.append(cells[column_number - 1].text)
        return column_content

    def find_record_by_username(self, username):
        for row_index, row in enumerate(self._rows, start=1):
            if username in self.get_row_content(row_index):
                return self.get_row_content(row_index)
        return None


if __name__ == "__main__":
    options = webdriver.ChromeOptions()
    options.add_argument("--window-size=1920,1080")
    driver = webdriver.Chrome(options=options)

    driver.get("https://demoqa.com/webtables")
    time.sleep(3)

    table = TableHandler(driver)

    # получение контента ячейки,
    print(table.get_cell_content(1, 1))

    # получение контента всего ряда,
    print("Содержимое ряда:", table.get_row_content(2))

    # получение контента всей колонки,
    print("Содержимое колонки:", table.get_column_content(3))

    # поиск записи по признаку (username и т.д
    print("Поиск по username", table.find_record_by_username("Cierra"))
